package com.yirui.bridge.udp.parser;

import com.alibaba.fastjson.JSON;
import com.yirui.bridge.udp.DataParser;
import io.netty.buffer.ByteBuf;
import io.netty.handler.codec.json.JsonObjectDecoder;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.LayeredConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.ssl.SSLContexts;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

import javax.net.ssl.SSLContext;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.util.*;

/**
 * @author Dujie
 * @create 2021/11/25
 * @since 1.0.0
 */
@Slf4j
public class Item79Parser implements DataParser {
    private RestTemplate  restTemplate ;
    private String url;
    private Map params;
    public static HttpComponentsClientHttpRequestFactory httpComponentsClientHttpRequestFactory() throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
        TrustStrategy acceptingTrustStrategy = (x509Certificates, authType) -> true;
        SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy).build();
        LayeredConnectionSocketFactory csf = new SSLConnectionSocketFactory(sslContext, new NoopHostnameVerifier());

        Registry<ConnectionSocketFactory> sfr = RegistryBuilder.<ConnectionSocketFactory>create().register("http", PlainConnectionSocketFactory.getSocketFactory()).register("https", csf != null ? csf : SSLConnectionSocketFactory.getSocketFactory()).build();
        PoolingHttpClientConnectionManager pollingConnectionManager = new PoolingHttpClientConnectionManager(sfr);
        pollingConnectionManager.setMaxTotal(10);
        pollingConnectionManager.setDefaultMaxPerRoute(10);

        CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(csf).setConnectionManager(pollingConnectionManager).build();
        HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
        factory.setHttpClient(httpClient);
        factory.setConnectTimeout(30000);
        factory.setReadTimeout(30000);
        factory.setConnectionRequestTimeout(30000);

        return factory;
    }
    public Item79Parser(){
        try {
            restTemplate = new RestTemplate(httpComponentsClientHttpRequestFactory());
        } catch (KeyStoreException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (KeyManagementException e) {
            e.printStackTrace();
        }
        url = System.getenv("POST_URL");
        String extParams = System.getenv("POST_EXT_PARAMS");
        log.info("POST_URL:{}  POST_EXT_PARAMS:{}",url, extParams);
        if(StringUtils.hasLength(extParams)){
            params = (Map)JSON.parse(extParams);
        }else{
            params = new HashMap();
        }

    }
    // //A5 AD 79 00 02 0B D5 FA 00 00 00 A7   (12)
    @Override
    public Object parse(ByteBuf buffer, int itemIndex, Map container) {
        byte index = buffer.getByte(5);
        float val = buffer.getShort(6)/100.0f;
        String key = String.format("%02x",itemIndex);
        Map list = (Map)container.get(key);
        if(list == null){
            list = new HashMap(50);
            container.put(key ,list);
        }
        list.put(index, val);
        /*

        Item79 i79 = (Item79) list.get(index);
        if(i79 == null){
            i79 = new Item79();
            list.put(index, i79);
        }

//        Item79 i79 = (Item79) container.get(key);
//        if(i79 == null){
//            i79 = new Item79();
//        }
        i79.setIndex(index);
        if(buffer.getByte(5) == 0xFF) {
            i79.setValue(-val);
        }else{
            i79.setValue(val);
        }*/
//        container.put(key ,i79);
        if(StringUtils.hasLength(url)) {
            params.put("res", list);
            params.put("item", itemIndex);
            String res = restTemplate.postForObject(url, params, String.class);
            if(log.isDebugEnabled()) {
                log.debug("POST_URL:{}  POST_PARAMS:{} 执行结果:{}", url, params, res);
            }
        }
        return null;
    }

    @Override
    public boolean isSingleValue() {
        return false;
    }
}
